$(function() {
  var btnDels = $(".btn-del");
  var btnConfirm = $("#btn-confirm");
  var btnUpdates = $(".btn-update");
  var essayName = $("[name=essay-name]");
  var essayUrl = $("[name=essay-url]");
  var essayLabels = $("[name=essay-labels]");
  var isUpdate = false;
  var collectionId = 0;

  btnConfirm.on("click", function(e) {
    //    console.log(essayName.val());
    if (isUpdate) {
      isUpdate = false;
      $.ajax({
        method: "post",
        url: "/admin/update-collection",
        data: {
          id: collectionId,
          essayName: essayName.val(),
          essayLabels: essayLabels.val(),
          essayUrl: essayUrl.val()
        },
        success: function(data) {
          if (data.code == 0) {
            location.reload();
          }
        }
      });
    } else {
      $.ajax({
        method: "post",
        url: "/admin/add-collection",
        data: {
          essayName: essayName.val(),
          essayLabels: essayLabels.val(),
          essayUrl: essayUrl.val()
        },
        success: function(data) {
          if (data.code == 0) {
            location.reload();
          }
        }
      });
    }
  });

  btnDels.on("click", function(e) {
    var id = $(this)
      .parent()
      .parent()
      .attr("id");
    $.ajax({
      method: "post",
      url: "/admin/del-collection",
      data: {
        id: id
      },
      success: function(data) {
        console.log(data);
        if (data.code == 0) {
          location.reload();
        }
      }
    });
  });

  btnUpdates.on("click", function(e) {
    isUpdate = true;
    var tr = $(this)
      .parent()
      .parent();
    collectionId = tr.attr("id");
    var tds = tr.find("td");
    var name = tds
      .eq(0)
      .text()
      .trim();
    var url = tds
      .eq(1)
      .text()
      .trim();
    var labels = tds
      .eq(2)
      .find("input")
      .val()
      .trim()
    essayName.val(name);
    essayUrl.val(url);
    essayLabels.val(labels);
    $("#modal-add").modal("show");
  });
});
